/**
 * Copyright (C), 2020-2020, 软件公司
 * FileName: ApplicationContextHelper.java
 * Author:   cakin
 * Date:     2020/8/5
 * Description: 获取环境中的bean
 */
package com.imooc.demo.common.util;

import org.springframework.beans.BeansException;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
import org.springframework.stereotype.Service;

/**
 * @className: ApplicationContextHelper
 * @description: 获取环境中的bean
 * @date: 2020/8/5
 * @author: cakin
 */
@Service
public class ApplicationContextHelper implements ApplicationContextAware {

    /**
     * 应用上下文
     */
    private static ApplicationContext applicationContext;

    @Override
    public void setApplicationContext(ApplicationContext context) throws BeansException {

        applicationContext = context;
    }

    /**
     * 获取bean
     *
     * @param clazz bean所属的类
     * @return T 返回的bean
     */
    public static <T> T popBean(Class<T> clazz) {
        //先判断是否为空
        if (applicationContext == null) {
            return null;
        }
        return applicationContext.getBean(clazz);
    }

    /**
     * 获取bean
     *
     * @param clazz bean所属的类
     * @param name bean的name
     * @return T 返回的bean
     */
    public static <T> T popBean(String name, Class<T> clazz) {
        if (applicationContext == null) {
            return null;
        }
        return applicationContext.getBean(name, clazz);
    }
}
